package com.alu.chess;

import com.alu.chess.pieces.Piece;

/**
 * 棋盘
 * 
 * @author jundonch
 * @date 2016/6/12
 *
 */
public class Board
{
	/**
	 * 存储所有存在的棋子
	 */
	private Piece[][] pieces = new Piece[8][8];
	
	/**
	 * 创建一个棋盘对象并自动初始化
	 */
	public Board()
	{
		this.initialize();
	}
	
	/**
	 * 初始化整个棋盘
	 */
	private void initialize()
	{		
		// 为第一行依次添加8个白色棋子
		pieces[0][0] = new Piece(Piece.WHITE, "r");
		pieces[0][1] = new Piece(Piece.WHITE, "n");
		pieces[0][2] = new Piece(Piece.WHITE, "b");
		pieces[0][3] = new Piece(Piece.WHITE, "q");
		pieces[0][4] = new Piece(Piece.WHITE, "k");
		pieces[0][5] = new Piece(Piece.WHITE, "b");
		pieces[0][6] = new Piece(Piece.WHITE, "n");
		pieces[0][7] = new Piece(Piece.WHITE, "r");
		
		// 为第2行添加8个白色的卒
		for(int i=0; i<8; i++)
		{
			pieces[1][i] = new Piece(Piece.WHITE, "p");
		}
		
		// 为第7行添加8个黑色的卒
		for(int i=0; i<8; i++)
		{
			pieces[6][i] = new Piece(Piece.BLACK, "P");
		}
		
		// 为第8行依次添加8个白色棋子
		pieces[7][0] = new Piece(Piece.BLACK, "R");
		pieces[7][1] = new Piece(Piece.BLACK, "N");
		pieces[7][2] = new Piece(Piece.BLACK, "B");
		pieces[7][3] = new Piece(Piece.BLACK, "Q");
		pieces[7][4] = new Piece(Piece.BLACK, "K");
		pieces[7][5] = new Piece(Piece.BLACK, "B");
		pieces[7][6] = new Piece(Piece.BLACK, "N");
		pieces[7][7] = new Piece(Piece.BLACK, "R");
	}
	
	/**
	 * 棋盘是否是空的
	 * 
	 * @return 布尔值，表示是否为空
	 */
	public boolean isEmpty()
	{
		boolean result = true;
		
		// 遍历循环整个棋子数组，一旦发现有不为空的立刻返回false
		for(int row=0;row<8;row++)
		{			
			for(int col=0;col<8;col++)
			{
				if(null != pieces[row][col])
				{
					return false;
				}
			}
		}
		
		return result;
	}

	/**
	 * 添加一个卒到棋盘里并返回包含当前所有棋子的列表
	 * 
	 * @param p 棋子
	 * @param row
	 * @param col
	 * @return 包含当前所有棋子的列表
	 */
	public Piece[][] addPawn(Piece p, int row, int col)
	{
		pieces[row][col] = p;		
		return pieces;
	}

	/**
	 * @return 可供使用的棋子数量
	 */
	public int availablePieces()
	{		
		int result = 0;
		// 遍历循环整个棋子数组并统计棋子数量
		for(int row=0;row<8;row++)
		{			
			for(int col=0;col<8;col++)
			{
				if(null != pieces[row][col])
				{
					result++;
				}
			}
		}
		return result;
	}

	/**
	 * 
	 * @param row 横坐标
	 * @param col 纵坐标
	 * @return 该坐标位置的棋子对象
	 */
	public Piece get(int row, int col)
	{
		return this.pieces[row][col];
	}

	/**
	 * @return 打印当前棋盘的布局
	 */
	public String print()
	{
		String result = "";
		for (int i = 7; i > -1; i--)
		{
			for (int j = 0; j < 8; j++)
			{
				if(null == pieces[i][j])
				{
					result += ".";
				}
				else
				{
					result += pieces[i][j].toString();
				}
			}
			result += System.lineSeparator();
		}
		return result;
	}
}
